package com.admin.action;

import com.admin.entity.Page;
import com.uni.entity.Commodity;
import com.uni.entity.User;
import com.uni.service.Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * --------------project-------------
 *
 * @Author Unirithe  - Mr.Chao
 * - CSDN:
 * https://blog.csdn.net/Unirithe
 * - GitHub:
 * https://github.com/unirithe
 * @create 2021/12/29 9:15
 * ------------------------------------------
 */
@WebServlet(name ="SelectAllCommodityPageableAction", urlPatterns = "/adminSelectAllCommodityPageable")
public class SelectAllCommodityPageableAction extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession();
        String pageInfo = req.getParameter("page");
        if ( pageInfo == null) {
            pageInfo = "1";
        }
        int pageNow = Integer.parseInt(pageInfo);
        int pageCount = 6;
        List<Commodity> commodities = Service.commodity.queryAll();
        for (Commodity commodity : commodities) {
            commodity.setTypeName(Service.commodity.queryTypeById(commodity.getTid()));
            commodity.setUserName(Service.user.queryUserById(commodity.getUid()).getName());
        }
        int totalRows= commodities.size();
        int totalPages = (totalRows % pageCount == 0) ? (totalRows / pageCount) : (totalRows / pageCount + 1);
        if(pageNow < 1) pageNow = 1;
        if(pageNow > totalPages) pageNow = totalPages;
        Page page = new Page(pageNow, pageCount, totalPages, totalRows);
        session.setAttribute("adminCommoityPage", page);
        session.setAttribute("commodityList", commodities);
        resp.sendRedirect("card_admin_option_commodity.jsp");
    }
}
